package com.ly.service;

import com.ly.component.threadpool.util.SpringTaskManager;

public class EngineService {
    private ConfigService configService;
    private CourseQueueService courseQueueService;
    private CaptchaService captchaService;
    private WebDriverService[] webDriverServices;

    public EngineService(int threadNum) {
        initConfig();
        initCourseQueue();
        initCaptcha();

        webDriverServices = new WebDriverService[threadNum];
        for (int i = 0; i < webDriverServices.length; i++) {
            webDriverServices[i] = new WebDriverService(i + "", configService, courseQueueService, captchaService);
        }
    }

    public void initConfig() {
        configService = new ConfigService();
    }

    public void initCourseQueue() {
        courseQueueService = new CourseQueueService();
    }

    public void initCaptcha() {
        captchaService = new CaptchaService();
    }

    public void start() {
        for (WebDriverService webDriverService : webDriverServices) {
            System.out.println("登录服务:" + webDriverService.getName());
            webDriverService.startLogin();
        }
        courseQueueService.setInfos(webDriverServices[0].getCourseInfo());
        for (WebDriverService webDriverService : webDriverServices) {
            SpringTaskManager.getInstance().submit(webDriverService.getName(), null, params -> {
                try {
                    webDriverService.start();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return true;
            }, params -> true);
        }
    }

    public void stop() {
        for (WebDriverService webDriverService : webDriverServices) {
            webDriverService.stop();
        }
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        for (WebDriverService webDriverService : webDriverServices) {
            SpringTaskManager.getInstance().cancel(webDriverService.getName());
        }
        try {
            captchaService.stop();
        } catch (Exception e) {

        }
        SpringTaskManager.getInstance().destroy();
    }
}
